var  app =require('express')()
var cors = require('cors')
var fs=require('fs');
let rimraf = require('rimraf');
require('babel-polyfill')

let {gPDF} =require('./clip_web_chrome_headless')
let getUrlParaObj = function(url){
    if(!url) return
    var search = url.split('?')[1];
    var param  = {};
    var arr = search.split('&');
    for(var k = 0, kk = arr.length; k < kk ; k++){
        var d = arr[k].split('=');
        param[d[0]] = decodeURI(d[1])
    }
    return param;
}


app.use(cors())
app.use(function(req, res, next){
  // console.log('%s %s', req.method, req.url);
  global.rightNow = (new Date).getTime()
  var requestURL = req.url;
  let match = requestURL.match(/([\d]*)\?template=(.*)*/)
  var hospitalId = decodeURI(match[1])
    console.log(getUrlParaObj('requestURL: ' +requestURL))
    var templateId = getUrlParaObj(requestURL).template || 1

  var style = getUrlParaObj(requestURL).style || 0
  console.log("接收到的医院名称是", hospitalId)
  if(hospitalId && hospitalId.length !== 0 && (hospitalId !== 'favicon.ico')){

    (async() => {
      console.log("PDF切图进行中...")
      var pdfFile = await gPDF(hospitalId,templateId, style);
      console.log('pdf地址', pdfFile)

      res.download(pdfFile,`${hospitalId}的报告.pdf`,function(err){
        if (err) {
          // 处理错误，请牢记可能只有部分内容被传输，所以
          // 检查一下res.headerSent
          console.log("传递发生错误",err)
        } else {
          console.log('传递成功！！')
          //将存放pdf的临时文件夹删除掉

          fs.unlink(pdfFile,()=>{
              console.log('文件'+pdfFile+'已经被删除了')
          })
        }
      })
    })();





  }else{
    res.send("请在链接的末尾加入医院名称, 形如http://10.0.1.135:3000/四川省人民医院")
  }
});

app.listen(3001, '0.0.0.0',()=>{
  console.log('截图服务器运行中...')
});